<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="My Personal Website For Blog">
  <meta name="author" content="黄宇辉">
  <meta name="keywords" content="learning note,hexo blog">
  <title>MyBatis的核心配置 - 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>ANONYMOUS</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-05-15 12:45">
      May 15, 2019 pm
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.2k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      33
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h2 id="学习笔记-MyBatis的核心配置"><a href="#学习笔记-MyBatis的核心配置" class="headerlink" title="学习笔记 : MyBatis的核心配置"></a>学习笔记 : MyBatis的核心配置</h2><h3 id="MyBatis的核心对象"><a href="#MyBatis的核心对象" class="headerlink" title="MyBatis的核心对象"></a>MyBatis的核心对象</h3><h4 id="SqlSessionFactory"><a href="#SqlSessionFactory" class="headerlink" title="SqlSessionFactory"></a>SqlSessionFactory</h4><p><em><code>SqlSessionFactory</code>是MyBatis中十分重要的对象,它是单个数据库映射关系经过编译后的内存镜像,其作用是创建<code>SqlSession</code>. SqlSessionFactory对象是线程安全的,它一旦被创建,在整个应用执行期间都会存在.如果我们多次地创建同一个数据库的SqlSessionFactory势必会耗尽数据库资源! 通常每一个数据库都会只对应一个SqlSessionFactory,所以在构建SqlSessionFactory时建议使用<code>单例模式</code>哟 !</em></p>
<h4 id="SqlSession"><a href="#SqlSession" class="headerlink" title="SqlSession"></a>SqlSession</h4><p><em><code>SqlSession</code>是MyBatis框架中另一个重要的对象,它是应用程序与持久层之间执行交互操作的一个单线程对象,其主要作用是执行持久化操作. 注意: 每一个线程都应该有一个自己的SqlSession实例,并且该实例是不能被共享的,同时<code>SqlSession</code>实例也是线程不安全的,因此其使用范围最好在一次请求或一个方法中,绝不能将其放在一个类的静态字段,实例或任何类型的管理范围中使用.使用后理应及时地关闭它 !</em></p>
<h3 id="配置文件"><a href="#配置文件" class="headerlink" title="配置文件"></a>配置文件</h3><h4 id="主要元素结构图"><a href="#主要元素结构图" class="headerlink" title="主要元素结构图"></a>主要元素结构图</h4><p><img src="/2019/05/15/MyBatis%E7%9A%84%E6%A0%B8%E5%BF%83%E9%85%8D%E7%BD%AE/MyBatis%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E4%B8%BB%E8%A6%81%E5%85%83%E7%B4%A0.png" srcset="/img/loading.gif" alt=" "></p>
<h3 id="映射文件"><a href="#映射文件" class="headerlink" title="映射文件"></a>映射文件</h3><p><em>官方简介 : MyBatis的真正强大在于它的映射语句,这是它的魔力所在.由于它的异常强大,映射器的XML文件就显得相对简单.如果拿它跟具有相同功能的JDBC代码进行对比,你会立即发现省掉了将近95%的代码! 俺喜欢简洁(✪ω✪) ~</em></p>
<h4 id="主要元素"><a href="#主要元素" class="headerlink" title="主要元素"></a>主要元素</h4><p><em>在映射文件中,<code>&lt;mapper&gt;</code>元素是映射文件的根元素,其它元素都是它的子元素,其子元素及其作用如下所示 :</em></p>
<ol>
<li><code>&lt;select&gt;</code> : 映射查询语句,可自定义参数,返回结果等.</li>
<li><code>&lt;insert&gt;</code> : 映射插入语句,执行后返回一个整数,代表插入到条数.</li>
<li><code>&lt;update&gt;</code> : 映射更新语句,执行后返回一个整数,代表更新的条数.</li>
<li><code>&lt;delete&gt;</code> : 映射删除语句,执行后返回一个整数,代表删除的条数.</li>
<li><code>&lt;sql&gt;</code> : 用于定义一部分SQL,然后可被其它语句引用此SQL.</li>
<li><code>&lt;cache-ref&gt;</code> : 其他命名空间缓存配置的引用.</li>
<li><code>&lt;resultMap&gt;</code> : 用于描述如何从数据库结果集中来加载数据.</li>
</ol>
<h4 id="简单案例"><a href="#简单案例" class="headerlink" title="简单案例"></a>简单案例</h4><p><em>MyBatis框架的强大之处体现在映射文件,下面使用上述主要元素来编写一个简单的CURE程序 ~</em></p>
<ol>
<li><p><em>数据表</em></p>
<div class="hljs"><pre><code class="hljs sql"><span class="hljs-comment"># 客户信息表(用于测试增删改查元素)</span>
<span class="hljs-keyword">create</span> <span class="hljs-keyword">table</span> t_customer (

	<span class="hljs-keyword">id</span> <span class="hljs-built_in">INT</span>(<span class="hljs-number">32</span>) PRIMARY <span class="hljs-keyword">KEY</span> AUTO_INCREMENT,
	username <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">20</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
	job <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">45</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
	phone <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">16</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>
	
)

<span class="hljs-comment"># 用户信息表(用于测试&lt;resultMap&gt;元素)</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> t_user(
	
	t_id <span class="hljs-built_in">INT</span> PRIMARY <span class="hljs-keyword">KEY</span> AUTO_INCREMENT,
	t_name <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">20</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
	t_age <span class="hljs-built_in">INT</span> <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>
)</code></pre></div>
</li>
<li><p><em>db.properties : 数据库配置信息</em></p>
<div class="hljs"><pre><code class="hljs t">#database configuration information
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://LOCALHOST/MyBatis?useSSL=false&amp;serverTimezone=UTC&amp;allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=GoodTime</code></pre></div>
</li>
<li><p><em>mybatis-config.xml : MyBatis核心配置文件</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE configuration
 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">configuration</span>&gt;</span>
	<span class="hljs-comment">&lt;!-- 数据库配置文件 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">properties</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">"db.properties"</span> /&gt;</span>
	<span class="hljs-comment">&lt;!-- 配置环境.默认环境id为MySQL --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">environments</span> <span class="hljs-attr">default</span>=<span class="hljs-string">"MySQL"</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">environment</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"MySQL"</span>&gt;</span>
			<span class="hljs-comment">&lt;!-- 使用JDBC事务管理 --&gt;</span>
			<span class="hljs-tag">&lt;<span class="hljs-name">transactionManager</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"JDBC"</span> /&gt;</span>
			<span class="hljs-comment">&lt;!-- 数据库连接池 --&gt;</span>
			<span class="hljs-tag">&lt;<span class="hljs-name">dataSource</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"POOLED"</span>&gt;</span>
				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"driver"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.driver&#125;"</span> /&gt;</span>
				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"url"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.url&#125;"</span> /&gt;</span>
				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.username&#125;"</span> /&gt;</span>
				<span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"$&#123;jdbc.password&#125;"</span> /&gt;</span>
			<span class="hljs-tag">&lt;/<span class="hljs-name">dataSource</span>&gt;</span>
		<span class="hljs-tag">&lt;/<span class="hljs-name">environment</span>&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">environments</span>&gt;</span>
	<span class="hljs-comment">&lt;!-- 将SQL映射文件注册到全局配置文件中 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">mappers</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">"pers/huangyuhui/mybatis/mapper/UserMapper.xml"</span>/&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">"pers/huangyuhui/mybatis/mapper/CustomerMapper.xml"</span>/&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">mappers</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">configuration</span>&gt;</span></code></pre></div>
</li>
<li><p><em>CustomerMapper.xml : 操作’t_customer’数据表的映射文件</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">namespace</span>=<span class="hljs-string">"pers.huangyuhui.mybatis.mapper.CustomerMapper"</span>&gt;</span>

	<span class="hljs-comment">&lt;!-- 使用&lt;sql&gt;元素定义可重用的sql代码片段,简化代码 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">sql</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"customerColumns"</span>&gt;</span>id,username,job,phone<span class="hljs-tag">&lt;/<span class="hljs-name">sql</span>&gt;</span>

	<span class="hljs-comment">&lt;!-- 使用&lt;insert&gt;元素查询客户信息 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"findCustomerById"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"Integer"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"pers.huangyuhui.mybatis.bean.Customer"</span>&gt;</span>
		select <span class="hljs-tag">&lt;<span class="hljs-name">include</span> <span class="hljs-attr">refid</span>=<span class="hljs-string">"customerColumns"</span>/&gt;</span> from t_customer where id = #&#123;id&#125;
	<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
	
	<span class="hljs-comment">&lt;!-- 使用&lt;insert&gt;元素添加客户信息并返回数据库生成的主键值 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">insert</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"addCustomer"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"pers.huangyuhui.mybatis.bean.Customer"</span> <span class="hljs-attr">keyProperty</span>=<span class="hljs-string">"id"</span> <span class="hljs-attr">useGeneratedKeys</span>=<span class="hljs-string">"true"</span>&gt;</span>
		insert into t_customer(username,job,phone) values(#&#123;username&#125;,#&#123;job&#125;,#&#123;phone&#125;)
	<span class="hljs-tag">&lt;/<span class="hljs-name">insert</span>&gt;</span>
	
	<span class="hljs-comment">&lt;!-- 使用&lt;insert&gt;元素添加客户信息并使用MyBatis提供的方式生成主键值 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">insert</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"addCustomer2"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"pers.huangyuhui.mybatis.bean.Customer"</span> &gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">selectKey</span> <span class="hljs-attr">keyProperty</span>=<span class="hljs-string">"id"</span> <span class="hljs-attr">resultType</span>=<span class="hljs-string">"Integer"</span> <span class="hljs-attr">order</span>=<span class="hljs-string">"BEFORE"</span>&gt;</span>
			select if(max(id) is null,1,max(id)+1) as newId from t_customer
		<span class="hljs-tag">&lt;/<span class="hljs-name">selectKey</span>&gt;</span>
		insert into t_customer(id,username,job,phone) values(#&#123;id&#125;,#&#123;username&#125;,#&#123;job&#125;,#&#123;phone&#125;)
	<span class="hljs-tag">&lt;/<span class="hljs-name">insert</span>&gt;</span>
	
	<span class="hljs-comment">&lt;!-- 使用&lt;update&gt;元素更新客户信息 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">update</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"updateCustomerById"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"pers.huangyuhui.mybatis.bean.Customer"</span>&gt;</span>
		update t_customer set username=#&#123;username&#125;,job=#&#123;job&#125;,phone=#&#123;phone&#125; where id = #&#123;id&#125;
	<span class="hljs-tag">&lt;/<span class="hljs-name">update</span>&gt;</span>
	
	<span class="hljs-comment">&lt;!-- 使用&lt;delete&gt;元素删除客户信息 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">delete</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"deleteCustomerById"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"Integer"</span>&gt;</span>
		delete from t_customer where id = #&#123;id&#125;
	<span class="hljs-tag">&lt;/<span class="hljs-name">delete</span>&gt;</span>
	
<span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span></code></pre></div>
</li>
<li><p><em>UserMapper.xml : 操作’t_user’数据表的映射文件</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">mapper</span> <span class="hljs-attr">namespace</span>=<span class="hljs-string">"pers.huangyuhui.mybatis.mapper.UserMapper"</span>&gt;</span>
	<span class="hljs-comment">&lt;!-- &lt;resultMap&gt;元素可解决数据表中的列与需要返回的对象的属性名可能不一致的问题	 --&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">resultMap</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"pers.huangyuhui.mybatis.bean.User"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"resultMap"</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">id</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"id"</span> <span class="hljs-attr">column</span>=<span class="hljs-string">"t_id"</span>/&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">result</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">column</span>=<span class="hljs-string">"t_name"</span>/&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">result</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">column</span>=<span class="hljs-string">"t_age"</span>/&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">resultMap</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"findAllUser"</span> <span class="hljs-attr">resultMap</span>=<span class="hljs-string">"resultMap"</span>&gt;</span>
		select t_id,t_name,t_age from t_user
	<span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">mapper</span>&gt;</span></code></pre></div>
</li>
<li><p><em>MyBatisUtils.java : MyBatis工具类</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.mybatis.util;

<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.io.Reader;

<span class="hljs-keyword">import</span> org.apache.ibatis.io.Resources;
<span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSession;
<span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSessionFactory;
<span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSessionFactoryBuilder;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: MyBatisUtils
 * <span class="hljs-doctag">@Description</span>: MyBatis工具类
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: May 18, 2019 3:59:18 PM
 *
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyBatisUtils</span> </span>&#123;

	<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">MyBatisUtils</span><span class="hljs-params">()</span> </span>&#123;

	&#125;

	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> SqlSessionFactory sqlSessionFactory = <span class="hljs-keyword">null</span>;

	<span class="hljs-keyword">static</span> &#123;
		<span class="hljs-comment">// 使用MyBatis提供的Resources类加载MyBatis的配置文件</span>
		<span class="hljs-keyword">try</span> (Reader reader = Resources.getResourceAsReader(<span class="hljs-string">"mybatis-config.xml"</span>);) &#123;
			<span class="hljs-comment">// 构建SqlSessionFactory工厂</span>
			sqlSessionFactory = <span class="hljs-keyword">new</span> SqlSessionFactoryBuilder().build(reader);
		&#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;
			e.printStackTrace();
		&#125;
	&#125;

	<span class="hljs-comment">// 获取SqlSession对象的静态方法</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> SqlSession <span class="hljs-title">getSession</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> sqlSessionFactory.openSession();
	&#125;
&#125;</code></pre></div>
</li>
<li><p><em>MyBatisTest.java : 测试类</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.mybatis.test;

<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">import</span> org.apache.ibatis.session.SqlSession;
<span class="hljs-keyword">import</span> org.junit.BeforeClass;
<span class="hljs-keyword">import</span> org.junit.Ignore;
<span class="hljs-keyword">import</span> org.junit.Test;

<span class="hljs-keyword">import</span> pers.huangyuhui.mybatis.bean.Customer;
<span class="hljs-keyword">import</span> pers.huangyuhui.mybatis.bean.User;
<span class="hljs-keyword">import</span> pers.huangyuhui.mybatis.util.MyBatisUtils;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: MyBatisTest
 * <span class="hljs-doctag">@Description</span>: MyBatis核心配置: CURE
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: May 18, 2019 4:03:47 PM
 *
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyBatisTest</span> </span>&#123;

	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Customer customer;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String namespace = <span class="hljs-string">"pers.huangyuhui.mybatis.mapper.CustomerMapper."</span>;

	<span class="hljs-meta">@BeforeClass</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">init</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException </span>&#123;
		customer = <span class="hljs-keyword">new</span> Customer();
	&#125;

	<span class="hljs-meta">@Test</span>
	<span class="hljs-meta">@Ignore</span>
	<span class="hljs-comment">// 根据客户编id查询客户信息</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">findCustomerByIdTest</span><span class="hljs-params">()</span> </span>&#123;

		<span class="hljs-comment">// 获取SqlSession对象</span>
		SqlSession sqlSession = MyBatisUtils.getSession();

		<span class="hljs-comment">// 执行SqlSession的查询方法,并返回结果</span>
		Customer customerInfo = sqlSession.selectOne(namespace + <span class="hljs-string">"findCustomerById"</span>, <span class="hljs-number">1</span>);

		<span class="hljs-comment">// 输出查询结果信息</span>
		System.out.println(customerInfo);

		<span class="hljs-comment">// 关闭SqlSession</span>
		sqlSession.close();

	&#125;

	<span class="hljs-meta">@Test</span>
	<span class="hljs-meta">@Ignore</span>
	<span class="hljs-comment">// 插入客户信息并获取由数据库生成的主键值</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addCustomerTest</span><span class="hljs-params">()</span> </span>&#123;
		SqlSession sqlSession = MyBatisUtils.getSession();

		customer.setUsername(<span class="hljs-string">"YUbuntu0109"</span>);
		customer.setJob(<span class="hljs-string">"student ~"</span>);
		customer.setPhone(<span class="hljs-string">"15111111111"</span>);

		<span class="hljs-keyword">int</span> rows = sqlSession.insert(namespace + <span class="hljs-string">"addCustomer"</span>, customer);

		<span class="hljs-keyword">if</span> (rows &gt; <span class="hljs-number">0</span>) &#123;
			System.out.println(<span class="hljs-string">"插入数据的主键id值为: "</span> + customer.getId());
			System.out.println(<span class="hljs-string">"成功插入了 "</span> + rows + <span class="hljs-string">" 条数据哟 ~"</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			System.out.println(<span class="hljs-string">"插入数据操作失败 !"</span>);
		&#125;

		sqlSession.commit();
		sqlSession.close();
	&#125;

	<span class="hljs-meta">@Test</span>
	<span class="hljs-meta">@Ignore</span>
	<span class="hljs-comment">// 添加客户信息并使用MyBatis提供的方式生成主键值</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addCustomer2Test</span><span class="hljs-params">()</span> </span>&#123;
		SqlSession sqlSession = MyBatisUtils.getSession();

		customer.setUsername(<span class="hljs-string">"YUbuntu0109"</span>);
		customer.setJob(<span class="hljs-string">"student ~"</span>);
		customer.setPhone(<span class="hljs-string">"13111111111"</span>);

		<span class="hljs-keyword">int</span> rows = sqlSession.insert(namespace + <span class="hljs-string">"addCustomer2"</span>, customer);
		<span class="hljs-keyword">if</span> (rows &gt; <span class="hljs-number">0</span>) &#123;
			System.out.println(<span class="hljs-string">"mybatis生成的主键为: "</span> + customer.getId());
			System.out.println(<span class="hljs-string">"成功插入了 "</span> + rows + <span class="hljs-string">" 条数据哟 ~"</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			System.out.println(<span class="hljs-string">"插入数据操作失败 !"</span>);
		&#125;

		sqlSession.commit();
		sqlSession.close();
	&#125;

	<span class="hljs-meta">@Test</span>
	<span class="hljs-meta">@Ignore</span>
	<span class="hljs-comment">// 根据客户id更新客户信息</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">updateCustomerByIdTest</span><span class="hljs-params">()</span> </span>&#123;
		SqlSession sqlSession = MyBatisUtils.getSession();

		customer.setId(<span class="hljs-number">1</span>);
		customer.setUsername(<span class="hljs-string">"YUbuntu0109"</span>);
		customer.setJob(<span class="hljs-string">"speaker"</span>);

		<span class="hljs-keyword">int</span> rows = sqlSession.update(namespace + <span class="hljs-string">"updateCustomerById"</span>, customer);
		<span class="hljs-keyword">if</span> (rows &gt; <span class="hljs-number">0</span>) &#123;
			System.out.println(<span class="hljs-string">"成功更新了 "</span> + rows + <span class="hljs-string">" 条数据哟 ~"</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			System.out.println(<span class="hljs-string">"数据更新操作失败 !"</span>);
		&#125;

		sqlSession.commit();
		sqlSession.close();

	&#125;

	<span class="hljs-meta">@Test</span>
	<span class="hljs-meta">@Ignore</span>
	<span class="hljs-comment">// 根据客户id删除客户信息</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteCustomerById</span><span class="hljs-params">()</span> </span>&#123;

		SqlSession sqlSession = MyBatisUtils.getSession();
		<span class="hljs-keyword">int</span> rows = sqlSession.delete(namespace + <span class="hljs-string">"deleteCustomerById"</span>, <span class="hljs-number">1</span>);
		<span class="hljs-keyword">if</span> (rows &gt; <span class="hljs-number">0</span>) &#123;
			System.out.println(<span class="hljs-string">"成功删除了 "</span> + rows + <span class="hljs-string">" 条记录哟 ~"</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			System.out.println(<span class="hljs-string">"删除数据操作失败 !"</span>);
		&#125;

		sqlSession.commit();
		sqlSession.close();

	&#125;

	<span class="hljs-meta">@Test</span>
    <span class="hljs-meta">@Ignore</span>
	<span class="hljs-comment">// 使用&lt;resultMap&gt;元素查找`t_user`表中所有用户信息</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">findAllUserTest</span><span class="hljs-params">()</span> </span>&#123;

		SqlSession sqlSession = MyBatisUtils.getSession();

		List&lt;User&gt; users = sqlSession.selectList(<span class="hljs-string">"pers.huangyuhui.mybatis.mapper.UserMapper.findAllUser"</span>);
		<span class="hljs-keyword">for</span> (User user : users) &#123;
			System.out.println(user);
		&#125;

	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>log4j.properties : 日志配置文件</em></p>
<div class="hljs"><pre><code class="hljs t">#Global configuration
log4j.rootLogger=DEBUG,stdout
#Log configuration
log4j.logger.pers.huangyuhui.mybatis.test=TRACE
#Console configuration
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.layout.ConversionPattern=%5p [%t] - %m%n</code></pre></div></li>
</ol>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/MyBatis/">MyBatis</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2019/05/15/VOA-One-Hour-of-Exercise-a-Day-Fights-Damage-of-Sitting/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">VOA:One Hour of Exercise a Day Fights Damage of Sitting</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2019/05/14/Spring-Bean/">
                        <span class="hidden-mobile">Spring:Bean</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "MyBatis的核心配置&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  














</body>
</html>
